package gmusic.thread;

import gmusic.bo.OptionBean;
import gmusic.ma.bo.DemandeChargement;
import gmusic.ma.services.impl.MetalArchivesServicesImpl;
import gmusic.services.impl.GMusicServicesImpl;

import java.util.List;

import org.apache.log4j.Logger;

public class GMusicBGProcess extends Thread {

	private boolean activerThread = false;

	private final static Logger log = Logger.getLogger(GMusicBGProcess.class);

	private final static int NB_ERREURS_MAX = 3;

	private int nbErreurs = 0;

	public GMusicBGProcess() {
		try {
			OptionBean pref = GMusicServicesImpl.getInstance().getOption(
					"ACTIVATION_THREAD");
			if (pref.getValue().equalsIgnoreCase("1")) {
				activerThread = true;
				MetalArchivesServicesImpl.activerChargementInfo();
			}
		} catch (Exception e) {
			log
					.error("Erreur lors de la recuperation de la preference ACTIVATION_THREAD");
			activerThread = false;
		}
		if (activerThread) {
			log.info("Le thread est actif");
		}
	}

	@SuppressWarnings("static-access")
	public void run() {
		while (activerThread) {
			try {
				Thread.currentThread().sleep(5000);
			} catch (InterruptedException ie) {
				activerThread = false;
			}

			try {
				List<DemandeChargement> toPreLoad = MetalArchivesServicesImpl
						.getInstance().getDemandesChargementToPreLoad();

				if (toPreLoad.size() > 0) {
					log.info("PreChargement de " + toPreLoad.get(0).getAmaid());
					MetalArchivesServicesImpl.getInstance().preChargement(
							toPreLoad.get(0));
				} else {

					DemandeChargement dem = MetalArchivesServicesImpl
							.getInstance().getNextDemandeChargement();

					if (dem != null) {
						log.info("Chargement de " + dem.getAmaid());
						MetalArchivesServicesImpl.getInstance()
								.majArtistDataFromMAWebSite(dem.getAmaid());
						if (activerThread
								&& MetalArchivesServicesImpl
										.isChargementInfoActif()) {
							MetalArchivesServicesImpl.getInstance()
									.updateDemandeChargementStatut(dem,
											DemandeChargement.LOADED);
						}
					} else {
						MetalArchivesServicesImpl.getInstance()
								.ajoutDemandeChargementMAJAuto();
					}
				}
				// log.debug("Fin run thread...");
				nbErreurs = 0;
			} catch (Exception e) {
				log.error("Erreur lors du chargement des info [" + nbErreurs
						+ "]", e);
				nbErreurs++;
				if (nbErreurs == NB_ERREURS_MAX) {
					activerThread = false;
				}
			}
		}
		log.info("Arret du thread");
	}

	public void stopThread() {
		activerThread = false;
		MetalArchivesServicesImpl.desactiverChargementInfo();
		log.info("Demande d'arret du thread");
	}
}
